const vm = new Vue({
    el: '#eformapp',
    data: {
        formJson: {"widgetList":[],"formConfig":{"labelWidth":80,"labelPosition":"left","size":"","labelAlign":"label-left-align","cssCode":"","customClass":"","functions":"","layoutType":"PC","onFormCreated":"","onFormMounted":"","onFormDataChange":"","onFormValidate":""}},
        formData: {},
        optionData: {},
        templateId: '',
        dataId: '',
        dataLinkTable: '',
        // 显示默认的提交按钮
        showDefaultSubmitButton: false,

    },
    //https://www.yuque.com/variantdev/vform/pi1mff#mE6tm
    mounted() {
        // 初始化表单配置和数据
        this.dataId = T.p('dataId');
        let that = this;
        //从后端接口获取已保存的数据对象，并赋值给formData变量
        $.ajax({
            async: false,
            url: T.webRoot + '/eform/eformdata/info/' + this.dataId,
            type: 'GET',
            success: function(res) {
                if (res.code === 0) {
                    let newFormData = $.parseJSON(res.data.dataJson);
                    $.ajax({
                        async: false,
                        url: T.webRoot + '/eform/eformtemplate/info/' + res.data.templateId,
                        type: 'GET',
                        success: function(res) {
                            let templateConfig = $.parseJSON(res.data.templateConfig);
                            that.$refs.vFormRef.setFormJson(templateConfig);
                            that.$nextTick(() => {
                                that.$refs.vFormRef.setFormData(newFormData);
                                that.$refs.vFormRef.disableForm();
                            });
                        },
                        error: function(err) {
                            console.log('err', err)
                        }
                    });
                } else {
                    console.log('加载数据失败！');
                }
            },
            error: function(err) {
                console.log('err', err)
            }
        });
    },
    methods: {
        // 表单提交
        defaultSubmitForm: function() {
            let that = this;
            this.$refs.vFormRef.getFormData().then( function(formData) {
                // Form Validation OK
                console.log('submitForm1', JSON.stringify(formData));
                let data = {
                    'templateId': that.templateId,
                    'dataLinkTable': that.dataLinkTable,
                    'dataJson': JSON.stringify(formData),
                };
                $.ajax({
                    url: 'eform/eformdata/save',
                    type: 'post',
                    contentType: 'application/json',
                    data: JSON.stringify(data),
                    success: function(res) {
                        layer.msg(res.msg, {icon: 6});
                        window.close();
                    },
                    error: function(err) {
                        layer.msg('网络异常，请稍后重试！', {icon: 5});
                    }
                });
            }).catch( function(error) {
                // Form Validation Failed
                alert(error)
            })
        },

        downloadEform(){
            debugger;
            let that = this;
            this.showDefaultSubmitButton = false
            var target = document.getElementById('eformapp');
            target.style.background = "#FFFFFF";
            this.$refs.vFormRef.enableForm();
            layer.msg("加载中……", {icon: 6});
            target.style.paddingTop = '20px';

             setTimeout(function () { //设置超时2秒后关闭弹出层
                        layer.close();//关闭弹出层
                        that.showDefaultSubmitButton = true;
                        that.$refs.vFormRef.disableForm();

                 // html2canvas(target, {
                 //     onrendered:function(canvas) {
                 //         var contentWidth = canvas.width;
                 //         var contentHeight = canvas.height;
                 //
                 //         //一页pdf显示html页面生成的canvas高度;
                 //         var pageHeight = contentWidth / 592.28 * 841.89;
                 //         //未生成pdf的html页面高度
                 //         var leftHeight = contentHeight;
                 //         //页面偏移
                 //         var position = 0;
                 //         //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
                 //         var imgWidth = 595.28;
                 //         var imgHeight = 592.28/contentWidth * contentHeight;
                 //
                 //         var pageData = canvas.toDataURL('image/jpeg', 1.0);
                 //
                 //         var pdf = new jsPDF('', 'pt', 'a4');
                 //
                 //         //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
                 //         //当内容未超过pdf一页显示的范围，无需分页
                 //         if (leftHeight < pageHeight) {
                 //             pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
                 //         } else {
                 //             while(leftHeight > 0) {
                 //                 pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                 //                 leftHeight -= pageHeight;
                 //                 position -= 841.89;
                 //                 //避免添加空白页
                 //                 if(leftHeight > 0) {
                 //                     pdf.addPage();
                 //                 }
                 //             }
                 //         }
                 //
                 //         pdf.save("content.pdf");
                 //
                 //
                 //     }
                 // })

                 document.documentElement.scrollTop = 0;

                 document.body.scrollTop = 0;

                 html2canvas(target, {
                     allowTaint: false,
                     taintTest: false,
                     logging: false,
                     useCORS: true,
                     dpi: window.devicePixelRatio*4, //将分辨率提高到特定的DPI 提高四倍
                     scale:4 //按比例增加分辨率
                 }).then(canvas=>{
                     var pdf = new jsPDF('p', 'mm', 'a4');    //A4纸，纵向
                     var ctx = canvas.getContext('2d'),
                         a4w = 190, a4h = 277,    //A4大小，210mm x 297mm，四边各保留10mm的边距，显示区域190x277
                         imgHeight = Math.floor(a4h * canvas.width / a4w),    //按A4显示比例换算一页图像的像素高度
                         renderedHeight = 0;

                     while(renderedHeight < canvas.height) {
                         var page = document.createElement("canvas");
                         page.width = canvas.width;
                         page.height = Math.min(imgHeight, canvas.height - renderedHeight);//可能内容不足一页

                         //用getImageData剪裁指定区域，并画到前面创建的canvas对象中
                         page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0);
                         pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width));    //添加图像到页面，保留10mm边距

                         renderedHeight += imgHeight;
                         if(renderedHeight < canvas.height) {
                             pdf.addPage();//如果后面还有内容，添加一个空页
                         }
                         // delete page;
                     }
                     //保存文件
                     pdf.save( 'content.pdf')
                 })


             },1000);



        }
    }
});